package com.sl.au.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.Device;
import com.sl.au.entity.Module;
import com.sl.au.entity.ReplaceDevicePrice;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.ReplaceDevicePriceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sl.au.entity.ReplacementDevice;
import com.sl.au.entity.SinglePump;
import com.sl.au.service.ReplacementDeviceService;

/**
 * 备品备件管理
 */
@RestController
@RequestMapping(value = "/ui/replacementDevice")
public class ReplacementDeviceController extends BaseController {

	@Autowired
	ReplacementDeviceService replacementDeviceService;

	@Autowired
	ReplaceDevicePriceService replaceDevicePriceService;

	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	ExcelService excelService;

	/**
	 * 页面显示
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("replacementDevice/replacementDeviceIndex");
		String name="replacement"; 
		Module module = this.getPageModule(name);
		modelAndView.addObject("module", module);
		return modelAndView;
	}
	
	

	/**
	 * 获取页面数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		List<ReplacementDevice> replaces = null;
		Long count = null;
		replaces = replacementDeviceService.getPage(start, length, key, null, null);
		count = replacementDeviceService.getRepository().getCount(key);
		List<ReplacementDevice> newRplaces = new ArrayList<ReplacementDevice>();
		for(ReplacementDevice r:replaces){
			String parentId=r.getId();
			List<Attachment> a=attachmentService.getRepository().findByParentId(parentId);
			int num=a.size();
			r.setAttachNumber(num);
			newRplaces.add(r);
		}
		
		map.put("data", newRplaces);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 验证是否重复
	 */
	@RequestMapping(value="/replacementDeviceValidate",method = RequestMethod.GET)
	public Map<String,Object>codeValidate(HttpServletRequest request){
		Map<String,Object>map=new HashMap<String,Object>();
		String  replacementDeviceId=request.getParameter("id");
    	String	deviceName=request.getParameter("deviceName");
    	String	type=request.getParameter("standardType");
    	String	material=request.getParameter("material");
    	long count=0;
    	if(replacementDeviceId==null||replacementDeviceId.equals("")){
    		count=replacementDeviceService.getRepository().getReCount(deviceName, type, material);
    	}else{
    		List<ReplacementDevice>replacementDevices=replacementDeviceService.getRepository().findByDeviceNameAndTypeAndMaterial(deviceName, type, material);
    		if(!replacementDevices.isEmpty()){
    			if(!replacementDevices.get(0).getId().equals(replacementDeviceId)){
    				count=replacementDevices.size();
    			}
    		}
    	}
		map.put("code", count);
		return map;
	}
	/*
	 * 添加备件并保存到备件价格本
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Map<String, Object> saveReplace(HttpServletRequest request, @RequestBody ReplacementDevice replace) {
		Map<String, Object> map = new HashMap<String, Object>();
		replacementDeviceService.getRepository().save(replace);
		List<ReplaceDevicePrice> p = new ArrayList<ReplaceDevicePrice>();
		String deviceName = replace.getDeviceName();
		String material=replace.getMaterial();
		String type=replace.getType();
		ReplaceDevicePrice p1 = new ReplaceDevicePrice();
		p1.setReplacementDevice(replace);
		p1.setReDeviceName(deviceName);
		p1.setReMaterial(material);
		p1.setReType(type);
		p1.setSuperior("成套处");
		p.add(p1);
		ReplaceDevicePrice p2 = new ReplaceDevicePrice();
		p2.setReplacementDevice(replace);
		p2.setReDeviceName(deviceName);
		p2.setReMaterial(material);
		p2.setReType(type);
		p2.setSuperior("外贸处");
		p.add(p2);
		ReplaceDevicePrice p3 = new ReplaceDevicePrice();
		p3.setReplacementDevice(replace);
		p3.setReDeviceName(deviceName);
		p3.setReMaterial(material);
		p3.setReType(type);
		p3.setSuperior("销售处");
		p.add(p3);
		ReplaceDevicePrice p4 = new ReplaceDevicePrice();
		p4.setReplacementDevice(replace);
		p4.setReDeviceName(deviceName);
		p4.setReMaterial(material);
		p4.setReType(type);
		p4.setSuperior("售后服务处");
		p.add(p4);
		replaceDevicePriceService.getRepository().save(p);
		map.put("code", 0);
		return map;
	}

	/**
	 * 编辑保存一个备件
	 */
	@RequestMapping(method = RequestMethod.PATCH)
	public Map<String, Object> patchWeekly(@RequestBody ReplacementDevice replacementDevice) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		replacementDeviceService.patch(replacementDevice);
		code = 0;
		map.put("code", code);
		return map;
	}

	/**
	 * 删除成套设备
	 * 
	 * @return
	 */
	@RequestMapping(value = "/delReplacementDevice", method = RequestMethod.GET)
	public Map<String, Object> delReplacementDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<ReplacementDevice> replacementDevices = new ArrayList<ReplacementDevice>();
		for (int i = 0; i < id.length; i++) {
			String replacementDeviceId = id[i];
			replaceDevicePriceService.getRepository().deleteDevicePrice(replacementDeviceId);
			ReplacementDevice replacementDevice = new ReplacementDevice();
			replacementDevice.setId(replacementDeviceId);
			replacementDevices.add(replacementDevice);
			List<Attachment> attachments = new ArrayList<Attachment>();
			attachments = attachmentService.getRepository().findByParentId(replacementDeviceId);
			attachmentService.getRepository().deleteInBatch(attachments);
		}
		replacementDeviceService.getRepository().deleteInBatch(replacementDevices);
		map.put("code", 0);
		return map;
	}

	/**
	 * EXCEL导入处理 *
	 */
	@RequestMapping(value = "/import", method = RequestMethod.POST)
	public Map<String, Object> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		Map<String, Object> map = new HashMap<String, Object>();
		int code = -1;
		long count = -1;
		String saveFileName = attachmentService.upload(file);
		// 文件传后，再读取EXCEL写入数据库
		if (StringUtils.hasText(saveFileName)) {
			count = replacementDeviceService.importExcel(saveFileName);
			code = 0;
		}
		map.put("code", code);
		map.put("count", count);
		return map;
	}
	/*
	 * 查询导出excel，如果key='', 导出全部
	 */
	@RequestMapping(value = "export/{key}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<Resource> excelFile(@PathVariable String key,HttpServletRequest request) throws UnsupportedEncodingException {
		if(key.equals("null")) key="";
		List<ReplacementDevice> devices=replacementDeviceService.getPage(0, Integer.MAX_VALUE, key, null, null);
		return this.excelService.toExcel(devices, "备件备品.xlsx");
	}
	///导出选择项
		@RequestMapping(value = "/exportSelects/{key}", method = RequestMethod.GET)
		@ResponseBody
		public ResponseEntity<Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
				throws UnsupportedEncodingException {	
			String id[] = key.split(",");
			List<ReplacementDevice> devices = new ArrayList<ReplacementDevice>();
			for (int i = 0; i < id.length; i++) {
				String deviceId = id[i];
				ReplacementDevice d=replacementDeviceService.getRepository().findOne(deviceId);
				devices.add(d);
			}
			return this.excelService.toExcel(devices, "备件备品.xlsx");
		}
}
